package com.knshare.utils.Executor;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author rongxun.wu01
 * @product IntelliJ IDEA
 * @project KnShare
 * @Date 2023-05-06 15:38
 */
public class ThreadPoolExecutorService {

    private ThreadPoolExecutor executor;

    public  ThreadPoolExecutorService(ThreadPoolExecutor threadPoolExecutor){
        this.executor=threadPoolExecutor;
    }
    /**
     * 执行任务
     */
    public void execute(Runnable runnable) {
        if (runnable == null) {
            return;
        }
        executor.execute(runnable);
    }

    /**
     * 从线程池中移除任务
     */
    public void remove(Runnable runnable) {
        if (runnable == null) {
            return;
        }
        executor.remove(runnable);
    }

    /**
     * 提交线程
     *
     * @return
     */
    public Future<?> submit(Runnable runnable) {
        if (runnable == null) {
            return null;
        }
        return executor.submit(runnable);
    }

    public <T> Future<T> submit(Runnable task, T result) {
        if (task == null || result == null) {
            return null;
        }

        return executor.submit(task, result);
    }

    public <T> Future<T> submit(Callable<T> task) {
        if (task == null) {
            return null;
        }
        return executor.submit(task);
    }

    /**
     * 关闭线程池
     */
    public void shutDownThreadPool() {
        this.executor.shutdown();
    }

    /**
     * 关闭线程池
     */
    public void shutDownNew() {
        this.executor.shutdownNow();
    }

    /**
     * 关闭线程池 超过指定时间关闭
     */
    public void shutdownThreadPool(long timeout, TimeUnit unit) {
        this.executor.shutdown();
        try {
            if (!this.executor.awaitTermination(timeout, unit)) {
                this.executor.shutdownNow();
                return;
            }
        } catch (InterruptedException e) {
            this.executor.shutdownNow();
            Thread.interrupted();
        }
    }

}
